const Admin = require("../models/admin");
const { secret } = require("../config/config");
const { sign, verify } = require("jsonwebtoken");
const bcrypt = require("bcryptjs");


class AdminControl {
  async adminLogin (ctx)  {
    const { admin_name, admin_role, admin_password } = ctx.request.body;
    const result = await Admin.findOne({ where: { admin_name, admin_role } });
    if (!result) {
      ctx.body = {
        message: "用户不存在",
        statusCode: 404,
        data: {},
      };
      return;
    }

    if (!bcrypt.compareSync(admin_password, result.admin_password)) {
      ctx.body = {
        message: "密码错误",
        statusCode: 400,
        data: {},
      };
      return;
    }

    const { admin_id } = result.dataValues;
    try {
      let token = sign({ admin_id, admin_name, admin_role }, secret, {
        expiresIn: '2d',
      });
      ctx.body = {
        message: "登录成功",
        statusCode: 200,
        data: {
          token,
        },
      };
    } catch (error) {
      console.log(error);
      ctx.body = {
        message: "登录失败",
        statusCode: 500,
        data: {},
      };
    }
  };

  // 管理员注册
  async adminRegister (ctx)  {
    try {
      const res = await Admin.create({ ...ctx.request.body });
      ctx.body = {
        statusCode: 200,
        message: "添加数据成功",
      };
    } catch (error) {
      console.log(error);
      ctx.body = {
        statusCode: 500,
        message: "添加数据失败",
      };
      return;
    }
  };

  // 管理员身份是否过期
  async adminIsTimeOut (ctx)  {
    const token = ctx.header.authorization;
    try {
        await  verify(token.split(' ')[1], secret);
        ctx.body = {
          statusCode: 200,
          message: '令牌未过期'
        }
    } catch (error) {
        ctx.body = {
            message: '令牌已过期,请重新登录',
            statusCode: 401
          }
    }  
  };

  // 获取当前管理员信息
  async adminCurrentInfo (ctx) {
    const { admin_id } = ctx.state.user;
    const result = await Admin.findOne({
      where: { admin_id },
      attributes: { exclude: ["admin_password"] },
    });

    console.log(result)
    if (!result) {
      ctx.body = {
        statusCode: 404,
        message: "没有该用户数据",
      };
      return;
    }

    ctx.body = {
      message: "获取成功",
      statusCode: 200,
      data: {
        data: result,
      },
    };
  };

  // 查找一个管理员
  async adminFindOne (ctx) {
    const { adminId } = ctx.request.query
    const result = Admin.findOne({
        where: { admin_id: adminId },
        attributes: { exclude: ["admin_password"] },
      });
      if (!result) {
        ctx.body = {
          statusCode: 404,
          message: "没有该用户数据",
        };
        return;
      }
  
      ctx.body = {
        message: "登录成功",
        statusCode: 200,
        data: {
          data: result,
        },
    }
  };

  // 获取管理员列表
  async adminFindAll (ctx) {
    const limit = ctx.request.query.limit ? ctx.request.query.limit : 16
    const page = ctx.request.query.page ? ctx.request.query.page : 1
    const offset = Math.max(0, page - 1) * limit * 1

    try {
        const { data, count} = await Admin.findAndCountAll({
            limit: limit * 1,
            offset: offset,
            attributes: {
                exclude: ['admin_password']
            }
        })
    
        ctx.body = {
            message: '获取数据成功',
            statusCode: 200,
            data: {
              data: data,
              total: count
            }
        }
    } catch (error) {
        console.log(error)
        ctx.body = {
            message: '获取数据失败',
            statusCode: 500,
           data: {}
        }
    }
    
  };

  // 更新管理员信息
  async adminUpate  (ctx)  {
    const adminId = ctx.request.params.adminId
    const params = ctx.request.body
    const res = await Admin.update({...params }, {
        where: {
          admin_id: adminId
        }
      })

      if (res == 1) {
        ctx.body = {
          statusCode: 200,
          message: '修改数据成功' 
        }
      } else {
        ctx.body = {
          statusCode: 500,
          message: '修改数据失败' 
        }
      }
  };

  // 删除管理员
  async adminDelete  (ctx) {
    const adminId = ctx.request.params.adminId
    const res = await Admin.destroy({
        where: {
          admin_id: adminId
        }
      })
      if (res == 1) {
        ctx.body = {
          statusCode: 200,
          message: '删除数据成功' 
        }
      } else {
        ctx.body = {
          statusCode: 200,
          message: '删除数据失败' 
        }
      } 
  };
}

module.exports = new AdminControl();
